<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-03-30
 * Time: 14:04
 */

namespace App\Services\Impl;


use App\Services\IWeinxinQyService;
use DOMDocument;
use WXBizMsgCrypt;

class WeixinQyServiceImpl implements IWeinxinQyService
{

    private $corpID;
    private $providerSecret;

    private $wxcpt;

    /**
     * WeixinQyServiceImpl constructor.
     */
    public function __construct($corpID,$providerSecret,$token,$encodingAesKey)
    {
        $this->corpID = config('services.WeixinCorpID');
        $this->providerSecret = config('services.WeixinProviderSecret');

        require_once(app_path('Libs/WeinxinQySdk/WXBizMsgCrypt.php'));

        $this->wxcpt = new WXBizMsgCrypt(config('services.WeixinToken'), config('services.WeixinEncodingAesKey'), $this->corpID);
    }

    public function VerifyURL($sMsgSignature, $sTimeStamp, $sNonce, $sEchoStr)
    {
        $sReplyEchoStr = "";
        $errCode = $this->wxcpt->VerifyURL($sMsgSignature, $sTimeStamp, $sNonce, $sEchoStr, $sReplyEchoStr);
        if ($errCode == 0) {
            return $sReplyEchoStr;
        } else {
            return $errCode;
        }
    }

    public function DecryptMsg($sMsgSignature, $sTimeStamp = null, $sNonce, $sPostData)
    {
        $sMsg = "";  // 解析之后的明文
        $errCode = $this->wxcpt->DecryptMsg($sMsgSignature, $sTimeStamp, $sNonce, $sPostData, $sMsg);
        if ($errCode == 0) {
            // 解密成功，sMsg即为xml格式的明文
            // 对明文的处理
            // For example:
            $xml = new DOMDocument();
            $xml->loadXML($sMsg);
            $content = $xml->getElementsByTagName('Content')->item(0)->nodeValue;
            return $content;
        } else {
            return $errCode;
        }
    }

    public function EncryptMsg($sReplyMsg, $sTimeStamp, $sNonce)
    {
        $sEncryptMsg = ""; //xml格式的密文
        $errCode = $this->wxcpt->EncryptMsg($sReplyMsg, $sTimeStamp, $sNonce, $sEncryptMsg);
        if ($errCode == 0) {
            return $sEncryptMsg;
        } else {
            return $errCode;
        }
    }


}